package com.blue.bluecode.sync;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by bluewaitor on 2015/4/10.
 */
public class AsyncImageDownloader extends AsyncTask<String, Void, Bitmap> {

    private ImageView imageView;
    private String url;

    public AsyncImageDownloader(ImageView imageView, String url) {
        this.imageView = imageView;
        this.url = url;
    }

    @Override
    protected Bitmap doInBackground(String... strings) {
        return getBitmapFromUrl(strings[0]);
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if(imageView.getTag().equals(url)){
            imageView.setImageBitmap(bitmap);
        }
    }

    public void showImageByAsync(ImageView imageView,String url){
        AsyncImageDownloader asyncImageDownloader = new AsyncImageDownloader(imageView, url);
        asyncImageDownloader.execute(url);
    }

    private static Bitmap getBitmapFromUrl(String urlString) {
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            is = new BufferedInputStream(conn.getInputStream());
            bitmap = BitmapFactory.decodeStream(is);
            conn.disconnect();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
